-- UISkyInstanceLab
-- Created by huangr Feb/19/2016
-- 天空副本死灵实验台界面

UISkyInstanceLab = class("UISkyInstanceLab", function()
    return cc.Layer:create();
end);

function UISkyInstanceLab.create(gridData)
    return UISkyInstanceLab.new(gridData);
end

-- 材料列表
local LAB_MATERIALS = {7024};

-- 制作动画播放时间
local PRODUCE_TIME = 1.2;

-- 制作完成后，界面停留的时间
local STAY_TIME = 0.6;

function UISkyInstanceLab:ctor(gridData)
    -- 初始化
    self:setName("UISkyInstanceLab");
    local node = cc.CSLoader:createNode("layout/lab/DungeonLab.csb");
    self:addChild(node);
    self.node = node;

    self:setLocalZOrder(UIMgr.TOP_MENU_ZORDER + 1);
    self.ringMaxLevel = DungeonLabM.getHarvenRingMaxLevel();

    -- 记录格子数据
    self.gridData = gridData;

    -- 注册事件处理回调函数
    self:registerEventCallback();

    -- 注册点击事件
    self:registerTouchEvent();

    -- 重绘
    self:redraw();

    -- 适配
    self:resize();
end

-- 适配
function UISkyInstanceLab:resize()
    local node = self.node;

    -- bg居中显示并充满整个屏幕
    AlignM.fitToScreen(node, "bg");

    -- CT居中并缩放至合适大小
    AlignM.alignToCenter(node, "CT");

    -- BT置于底部并缩放至合适大小
    AlignM.alignToBottomCenter(node, "BT");
end

-- 注册事件处理回调函数
function UISkyInstanceLab:registerEventCallback()
    -- 关注实验台升级装备的事件
    EventMgr.register("UISkyInstanceLab", event.LAB_UPGRADE_EQUIP, function(args)
        local classId = args.classId;
        local isSucc  = args.isSucc;

        local function showHint()
            local name = ItemM.query(classId, "name");
            local level = DungeonLabM.getHarvenRingLevel();

            alert(string.format(getLocStr("lab_upgrade_succ"), name, level));

            -- 播放奖励特效
            self:playBonusEffect(classId);
        end

        performWithDelay(self, showHint, STAY_TIME - 0.05);
    end);

    self:registerScriptHandler(function(eventType)
        if eventType == "exit" then
            cclog("UISkyInstanceLab 界面析构清理");

            -- 移除所有事件关注
            EventMgr.removeAll("UISkyInstanceLab");

            if UIDungeonMgr:getCurLevel() then
                UIDungeonMgr:getCurLevel():showMenu();
            end

        elseif eventType == "enter" then
            if UIDungeonMgr:getCurLevel() then
                UIDungeonMgr:getCurLevel():hideMenu();
            end
        end
    end);
end

-- 注册点击事件
function UISkyInstanceLab:registerTouchEvent()
    -- 注册返回按钮点击事件
    local node = self.node;
    local btnBack = findChildByName(node, "BT/btn_back");
    local function onBackClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            -- 关闭当前界面
            AudioM.playFx("button_return");
            UIMgr.getCurrentScene():removeFormByName("UISkyInstanceLab");
        end
    end
    AddBackEventHandler(self, btnBack, onBackClick);
    TextStyleM.setTextStyle(btnBack, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
    btnBack:setTitleText(getLocStr("btn_text_back"));

    -- 注册确定按钮点击事件
    local btnOk = findChildByName(node, "CT/btn_ok");
    local function onOkClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            AudioM.playFx("button_click");

            local ringLevel = DungeonLabM.getHarvenRingLevel();
            if ringLevel >= self.ringMaxLevel then
                alert(string.format(getLocStr("lab_equip_level_upper"), name));
                return;
            end

            -- 判断材料是否足够
            if not self:checkCost() then
                alert(getLocStr("lab_upgrade_lack"));
                return;
            end

            -- 按钮短暂置灰
            setClickFrequency(sender, PRODUCE_TIME + 0.7);

            -- 播放制作动画
            self:playProduceEffect();

            local function doCompound()
                -- 升级
                DungeonActionM.go("harven_ring_improve", 0, DungeonLabM.getSkyLabItemId());
            end

            performWithDelay(self, doCompound, PRODUCE_TIME);
        end
    end
    btnOk:addTouchEventListener(onOkClick);
end

-- 播放奖励特效
function UISkyInstanceLab:playBonusEffect(classId)
    -- 移除制作特效
    self:removeProduceEffect();

    -- 如果获得了物品，播放飞入包裹的动画
    if classId then
        -- 先显示物品图标
        local buildingImg = findChildByName(self.node, "CT/icon");
        local iconPath = getItemIconPath(ItemM.query(classId, "icon"));
        buildingImg:loadTexture(iconPath);

        -- 播放飞入动画
        local function playAnim()
            local grid = UIDungeonMgr.getCurLevel():getAllGrids()[18];
            pickupEquipEffect(grid, UIDungeonMgr.getCurLevel():getEquipNode(), iconPath, classId, 1);

            -- 获得道具音效
            AudioM.playFx("get_bone");

            -- 关闭界面
            UIMgr.getCurrentScene():removeFormByName("UISkyInstanceLab");
        end

        -- 短暂停留
        performWithDelay(self, playAnim, STAY_TIME);
    end
end

-- 移除制作动画
function UISkyInstanceLab:removeProduceEffect()
    local effectNode = findChildByName(self.node, "CT/effect_node");
    effectNode:removeAllChildren();
end

-- 播放制作动画
function UISkyInstanceLab:playProduceEffect()
    -- 播放制作特效
    local effectNode = findChildByName(self.node, "CT/effect_node");
    playEffect(effectNode, 1151);
end

-- 重绘
function UISkyInstanceLab:redraw()
    local descLabel  = findChildByName(self.node, "CT/desc");
    local iconImg    = findChildByName(self.node, "CT/icon");
    local titleLabel = findChildByName(self.node, "CT/title_node/title");
    local btnOk      = findChildByName(self.node, "CT/btn_ok");

    -- 查询建筑配置
    local class = self.gridData.class;
    local labId = self.gridData.labId;
    local labInfo = DungeonLabM.query(labId);
    local buildingInfo = BuildingBonusM.queryBuildingView(class);

    -- 标题
    titleLabel:setString(buildingInfo["title"]);

    -- 图片
    iconImg:loadTexture(getLevelItemIconPath(buildingInfo["icon"]));

    iconImg:setScale(1.0);
    TextStyleM.setTextStyle(btnOk, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
    TextStyleM.setArtWordTitleStyle(titleLabel);
    TextStyleM.setTextStyle(descLabel, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_DARK_BROWN);

    -- 获取待操作的装备编号
    local classId = DungeonLabM.getSkyLabItemId();

    -- 对话内容
    local dialog = buildingInfo["dialog"] .. "\n";

    -- 获得升级需求
    local cost = FormulaM.invoke("CALC_UPGRADE_HARVEN_RING_COST");
    local itemName = ItemM.query(cost[2], "name");
    local costNum = cost[3];
    local costText = string.format(getLocStr("lab_cost_desc2"), itemName, costNum);
    local dialog = dialog .. costText;

    local viewText = "";
    local ringName = ItemM.query(DungeonLabM.getSkyLabItemId(), "name");
    local ringLevel = DungeonLabM.getHarvenRingLevel();
    viewText = string.format(getLocStr("lab_button_text2"), ringName, ringLevel + 1);

    local isHas = EquipM.hasEquipment(classId);

    if not isHas then
        -- 升级按钮不可用
        btnOk:setBright(false);
        btnOk:setTouchEnabled(false);
    else
        if ringLevel >= self.ringMaxLevel then
            -- 升级按钮不可用
            btnOk:setBright(false);
            btnOk:setTouchEnabled(false);

            viewText = getLocStr("max_level_yet");
        else
            -- 升级按钮可用
            btnOk:setBright(true);
            btnOk:setTouchEnabled(true);
        end
    end

    applyString(descLabel, dialog);
    btnOk:setTitleText(viewText);

    self:redrawCost();
end

-- 重绘消耗
function UISkyInstanceLab:redrawCost(cost)
    local costPart = findChildByName(self.node, "CT/cost_part");
    local childA = findChildByName(costPart, "cost_node1");
    childA:setVisible(false);

    local childB = findChildByName(costPart, "cost_node3");
    childB:setVisible(false);

    -- 获得升级需求
    local cost = FormulaM.invoke("CALC_UPGRADE_HARVEN_RING_COST");
    local id = cost[2];

    local child = findChildByName(costPart, "cost_node" .. 2);

        -- 显示材料图标
    local iconImg = findChildByName(child, "icon");
    local iconPath = getItemIconPath(ItemM.query(id, "icon"));
    iconImg:loadTexture(iconPath);
    iconImg:setScale(0.7);
    iconImg:setPositionY(10);

    -- 显示数量信息
    local amountLabel = findChildByName(child, "amount");
    local needAmount = cost[3];
    local curAmount = ItemM.getAmount(ME.user, id);

    -- 消耗不足时，显示红色
    if curAmount < needAmount then
        TextStyleM.setTextStyle(amountLabel, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_DARK_RED);
    else
        TextStyleM.setTextStyle(amountLabel, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_BEIGE);
    end

    if needAmount <= 0 then
        -- 无需消耗
        amountLabel:setString(curAmount .. "/-");
    else

        amountLabel:setString(curAmount .. "/" .. needAmount);
    end

    local ringLevel = DungeonLabM.getHarvenRingLevel();
    if ringLevel >= self.ringMaxLevel then
        --
        TextStyleM.setTextStyle(amountLabel, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_WHITE, true);
        -- 无需消耗
        amountLabel:setString(curAmount .. "/-");
    end
end

-- 检查消耗是否足够
function UISkyInstanceLab:checkCost()
    local arr = FormulaM.invoke("CALC_UPGRADE_HARVEN_RING_COST");
    if ItemM.getAmount(ME.user, arr[2]) < arr[3] then
        trace("UISkyInstanceLab", "物品(%d)数量不足。", arr[2]);
        return false;
    end

    return true;
end
